package com.java.advance.ticket.service.impl;

import com.java.advance.ticket.dao.TicketMapper;
import com.java.advance.ticket.redis.RedisManager;
import com.java.advance.ticket.redis.key.TicketKey;
import com.java.advance.ticket.service.ITicketService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 方案一：通过互斥锁，重建缓存
 * Created by yangminghua on 2019/4/16.
 */
@Slf4j
@Service("ticketLockService")
public class TicketServiceLockImpl implements ITicketService {

    @Autowired
    TicketMapper ticketMapper;

    @Resource(name = "RedisManager")
    RedisManager redisManager;

    private Lock lock = new ReentrantLock();

    @Override
    public Object queryTicketStock(String ticketSeq) {
        log.info("ticketSeq:{}", ticketSeq);
        //1、先从缓存中获取该车次的余票信息
        Integer stock = redisManager.get(TicketKey.queryTicketStock, ticketSeq, Integer.class);
        log.info("stock:{}", stock);
        if (stock != null) {
            log.info("从缓存获取数据成功");
            return stock;
        }
        //第一种方法，使用锁synchronized机制
//        synchronized (stock) {
//        }
        //第二种方法，使用锁lock机制
        lock.lock();
        try {
            stock = redisManager.get(TicketKey.queryTicketStock, ticketSeq, Integer.class);
            log.info("stock:{}", stock);
            if (stock != null) {
                log.info("从缓存获取数据成功");
                return stock;
            }
            //2、缓存中没有则取数据库
            stock = ticketMapper.selectByPrimaryKey(ticketSeq).getTicketStock();
            log.info("从数据库获取数据成功");
            //3、塞到缓存当中，120秒过期
            redisManager.set(TicketKey.queryTicketStock, ticketSeq, stock);
        } finally {
            lock.unlock();
        }
        //4、返回
        return stock;
    }
}
